package il.ac.tau.cvws.scrabblesidekick.server.engine.storage;

import il.ac.tau.cvws.scrabblesidekick.server.constant.FileConstants;
import il.ac.tau.cvws.scrabblesidekick.server.engine.recoginition.TileImageMap;
import il.ac.tau.cvws.scrabblesidekick.server.util.cv.CvUtil;
import il.ac.tau.cvws.scrabblesidekick.server.util.file.FileUtil;
import il.ac.tau.cvws.scrabblesidekick.shared.datatype.StorageDataKey;
import il.ac.tau.cvws.scrabblesidekick.shared.datatype.game.Tile;

import java.util.Iterator;
import java.util.Map;

import com.googlecode.javacv.cpp.opencv_core.IplImage;

/* Storage for the tile-images extracted during calibration.
 */
public class TileImageStorage
{
	/* Retrieves a tile-image map from the storage.
	 */
	public TileImageMap getTileImageMap(long key) throws StorageException
	{
		TileImageMap imageMap = new TileImageMap();
		
		String storagePath = getStoragePath(key);
		
		String[] files = FileUtil.getDirectoryFiles(FileConstants.WORKING_DIR + storagePath);
		
		if ((files == null) || (files.length == 0))
		{
			throw new StorageException(StorageException.INVALID_KEY);
		}
		
		for (String file : files)
		{
			IplImage image = CvUtil.loadImage(storagePath + file, true);
			String truncatedName = file.substring(0, file.indexOf('.'));
			
			imageMap.put(new Tile(Integer.parseInt(truncatedName), 1), image);
		}
		
		return imageMap;
	}
	
	/* Stores a tile-image map and returns the associated key.
	 */
	public StorageDataKey setTileImageMap(TileImageMap map)
	{
		StorageDataKey key = StorageKeyGenerator.generateStorageKey();
		
		FileUtil.createDirectory(FileConstants.WORKING_DIR + getStoragePath(key.getKey()));
		
		for (Iterator<Map.Entry<Tile, IplImage>> ite = map.iterator(); ite.hasNext(); )
		{
			Map.Entry<Tile, IplImage> entry = ite.next();
			
			StringBuilder builder = new StringBuilder();
			builder.append(getStoragePath(key.getKey())).append(entry.getKey().getIndex()).append(FileConstants.PIC_FORMAT);

			CvUtil.saveImage(entry.getValue(), builder.toString());	
		}
		
		return key;
	}
	
	private String getStoragePath(long storageKey)
	{
		StringBuilder builder = new StringBuilder();
		
		builder.append(FileConstants.TILE_LAYOUT_STORAGE_FOLDER).append(storageKey).append("\\");
		
		return builder.toString();
	}
}
